1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.math;
18
19 import static com.google.common.math.MathBenchmarking.ARRAY_MASK;
20 import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
21 import static com.google.common.math.MathBenchmarking.randomDouble;
22 import static com.google.common.math.MathBenchmarking.randomPositiveDouble;
23
24 import com.google.caliper.BeforeExperiment;
25 import com.google.caliper.Benchmark;
26 import com.google.caliper.Param;
27 import com.google.common.math.DoubleMath;
28
29 import java.math.RoundingMode;
30
31
32
33
34
35
36 public class DoubleMathRoundingBenchmark {
37 private static final double[] doubleInIntRange = new double[ARRAY_SIZE];
38 private static final double[] doubleInLongRange = new double[ARRAY_SIZE];
39 private static final double[] positiveDoubles = new double[ARRAY_SIZE];
40
41 @Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"})
42 RoundingMode mode;
43
44 @BeforeExperiment
45 void setUp() {
46 for (int i = 0; i < ARRAY_SIZE; i++) {
47 doubleInIntRange[i] = randomDouble(Integer.SIZE - 2);
48 doubleInLongRange[i] = randomDouble(Long.SIZE - 2);
49 positiveDoubles[i] = randomPositiveDouble();
50 }
51 }
52
53 @Benchmark int roundToInt(int reps) {
54 int tmp = 0;
55 for (int i = 0; i < reps; i++) {
56 int j = i & ARRAY_MASK;
57 tmp += DoubleMath.roundToInt(doubleInIntRange[j], mode);
58 }
59 return tmp;
60 }
61
62 @Benchmark long roundToLong(int reps) {
63 long tmp = 0;
64 for (int i = 0; i < reps; i++) {
65 int j = i & ARRAY_MASK;
66 tmp += DoubleMath.roundToLong(doubleInLongRange[j], mode);
67 }
68 return tmp;
69 }
70
71 @Benchmark int roundToBigInteger(int reps) {
72 int tmp = 0;
73 for (int i = 0; i < reps; i++) {
74 int j = i & ARRAY_MASK;
75 tmp += DoubleMath.roundToBigInteger(positiveDoubles[j], mode).intValue();
76 }
77 return tmp;
78 }
79
80 @Benchmark int log2Round(int reps) {
81 int tmp = 0;
82 for (int i = 0; i < reps; i++) {
83 int j = i & ARRAY_MASK;
84 tmp += DoubleMath.log2(positiveDoubles[j], mode);
85 }
86 return tmp;
87 }
88 }